package org.news.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.news.web.domain.Favorites;
import org.news.web.domain.News;
import org.news.web.domain.Users;
import org.news.web.mapper.NewsMapper;
import org.news.web.mapper.UsersMapper;
import org.springframework.stereotype.Service;
import org.news.web.domain.bo.HistoryBo;
import org.news.web.domain.vo.HistoryVo;
import org.news.web.domain.History;
import org.news.web.mapper.HistoryMapper;
import org.news.web.service.IHistoryService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 历史记录Service业务层处理
 *
 * @author Gu Ci
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class HistoryServiceImpl implements IHistoryService {

    private final HistoryMapper baseMapper;

    private final UsersMapper usersMapper;

    private final NewsMapper newsMapper;

    /**
     * 查询历史记录
     */
    @Override
    public HistoryVo queryById(Long historyId){
        return baseMapper.selectVoById(historyId);
    }

    /**
     * 查询历史记录列表
     */
    @Override
    public TableDataInfo<HistoryVo> queryPageList(HistoryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<History> lqw = buildQueryWrapper(bo);
        Page<HistoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);


        if(ObjectUtil.isNotNull(result.getRecords()) && result.getRecords().size() >0){
            Set<Long> collect = result.getRecords().stream().map(item -> {
                return item.getUserId();
            }).collect(Collectors.toSet());

            List<Users> users = usersMapper.selectList(new LambdaQueryWrapper<Users>().in(Users::getUserId, collect));
            users.forEach(user ->{
                result.getRecords().stream().forEach(item ->{
                    if(item.getUserId() == user.getUserId()){
                        item.setUsername(user.getUsername());
                    }
                });
            });
        }
        /**
         * 获取新闻标题
         */
        if(ObjectUtil.isNotNull(result.getRecords()) && result.getRecords().size() >0){
            Set<Long> collect = result.getRecords().stream().map(item -> {
                return item.getNewsId();
            }).collect(Collectors.toSet());
            List<News> news = newsMapper.selectList(new LambdaQueryWrapper<News>().in(News::getNewsId, collect));

            news.stream().forEach(New->{
                result.getRecords().forEach(item ->{
                    if(New.getNewsId() == item.getNewsId()){
                        item.setTitle(New.getTitle());
                    }
                });
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询历史记录列表
     */
    @Override
    public List<HistoryVo> queryList(HistoryBo bo) {
        LambdaQueryWrapper<History> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<History> buildQueryWrapper(HistoryBo bo) {
        LambdaQueryWrapper<History> lqw = Wrappers.lambdaQuery();
        if(bo.getUserId() == null){
            Set<Long> userIds = null;
            if(StringUtils.isNotBlank(bo.getUsername())){
                List<Users> username = usersMapper.selectList(new QueryWrapper<Users>().like("username", bo.getUsername()));
                if(ObjectUtil.isNotNull(username) && username.size() >0){
                    userIds = username.stream().map(Users::getUserId).collect(Collectors.toSet());
                }else{
//                查询不到用户 给一个查不到的id
                    userIds = new HashSet<>();
                    userIds.add(-1l);
                }
            }
            lqw.in(userIds!= null, History::getUserId, userIds);
        }else{
            lqw.eq(History::getUserId,bo.getUserId());
        }

        return lqw;
    }

    /**
     * 新增和修改历史记录
     */
    @Override
    public Boolean insertByBo(HistoryBo bo) {
        History add = MapstructUtils.convert(bo, History.class);
        /**
         * 查询是否存在该历史记录
         */
        History history = baseMapper.selectOne(new LambdaQueryWrapper<History>().eq(History::getUserId, add.getUserId()).eq(History::getNewsId, add.getNewsId()));
        if(ObjectUtil.isNotNull(history)){
            history.setActionTime(new Date());
            int update = baseMapper.updateById(history);
            return update>0;
        }
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setHistoryId(add.getHistoryId());
        }
        return flag;
    }

    /**
     * 修改历史记录
     */
    @Override
    public Boolean updateByBo(HistoryBo bo) {
        History update = MapstructUtils.convert(bo, History.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(History entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除历史记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
